package com.by.order.service.impl;

import org.springframework.stereotype.Component;

import java.net.NetworkInterface;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Enumeration;

/**
 * 雪花算法ID生成器
 * 生成全局唯一的ID
 */
@Component
public class SnowflakeIdGenerator {
    
    // 起始时间戳 (2022-01-01)
    private static final long START_TIMESTAMP = 1640995200000L;
    
    // 每部分的位数
    private static final long SEQUENCE_BIT = 12;  // 序列号占用的位数
    private static final long MACHINE_BIT = 10;   // 机器标识占用的位数
    
    // 每部分的最大值
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    private static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    
    // 每部分向左的位移
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    
    private final long machineId;  // 机器ID
    private long sequence = 0L;    // 序列号
    private long lastTimestamp = -1L;  // 上一次时间戳
    
    public SnowflakeIdGenerator() {
        this.machineId = getMachineNum();
        if (this.machineId > MAX_MACHINE_NUM || this.machineId < 0) {
            throw new IllegalArgumentException("machineId must be between 0 and " + MAX_MACHINE_NUM);
        }
    }
    
    /**
     * 生成下一个ID
     * 
     * @return 唯一ID
     */
    public synchronized long nextId() {
        long currTimestamp = getNewTimestamp();
        if (currTimestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }
        
        if (currTimestamp == lastTimestamp) {
            // 相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currTimestamp = getNextMill();
            }
        } else {
            // 不同毫秒内，序列号置为0
            sequence = 0L;
        }
        
        lastTimestamp = currTimestamp;
        
        // 时间戳部分 | 机器标识部分 | 序列号部分
        return (currTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }
    
    /**
     * 获取下一个毫秒数
     * 
     * @return 下一个毫秒数
     */
    private long getNextMill() {
        long mill = getNewTimestamp();
        while (mill <= lastTimestamp) {
            mill = getNewTimestamp();
        }
        return mill;
    }
    
    /**
     * 获取当前时间戳
     * 
     * @return 当前时间戳
     */
    private long getNewTimestamp() {
        return Instant.now().toEpochMilli();
    }
    
    /**
     * 获取机器ID
     * 
     * @return 机器ID
     */
    private long getMachineNum() {
        try {
            StringBuilder sb = new StringBuilder();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    for (byte b : mac) {
                        sb.append(String.format("%02X", b));
                    }
                }
            }
            
            // 使用MAC地址的哈希码作为机器ID
            return Math.abs(sb.toString().hashCode()) % (MAX_MACHINE_NUM + 1);
        } catch (Exception e) {
            // 如果获取MAC地址失败，则使用随机数
            return new SecureRandom().nextInt((int) MAX_MACHINE_NUM + 1);
        }
    }
}